﻿using System.Collections.Generic;
using System.IO;
using HighPerformanceLog.V2;

namespace ProcessBarDemo.UpdateFramework
{
    public class UpdateManager
    {
        public List<DownloadFileInfo> FilesToDownload { get; private set; }
        public long TotalSize => XMLHelper.totalSize;

        private string downloadPath;

        public void LoadUpdateConfig(string xmlPath, string downloadPath)
        {
            FilesToDownload = XMLHelper.LoadFiles(xmlPath);
            
            this.downloadPath = downloadPath;
            Directory.CreateDirectory(downloadPath);
        }

        public void StartDownloadAll()
        {
            ProgressReporter.Init(XMLHelper.totalSize);
            
            foreach (var file in FilesToDownload)
            {
                string url = XMLHelper.PrefixURL + XMLHelper.VersionName + "/" + file.RelaventPath;
                string savePath = Path.Combine(downloadPath, file.RelaventPath);
                string saveDir = Path.GetDirectoryName(savePath);
                Directory.CreateDirectory(saveDir);

                int threadCount = ThreadCountDecider.GetThreadCount(file.Filesize);
                HWLogger.DebugLog($"准备下载: {file.RelaventPath} 线程数: {threadCount}");

                DownloadService.DownloadFile(url, saveDir, threadCount, file.Filesize, Path.GetFileName(savePath));
            }
        }
    }
}
